﻿using System;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace ZL.Web.Utility.Serializer
{
    public class XmlSerializerHelper
    {
        public static T DeserializeWithStirng<T>(string xmlString) where T : new()
        {
            if (string.IsNullOrEmpty(xmlString))
                return new T();
            try
            {
                using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(xmlString)))
                {
                    var xmlSerializer = new XmlSerializer(typeof (T));
                    return (T) xmlSerializer.Deserialize(stream);
                }
            }
            catch (Exception ex)
            {
                return new T();
            }
        }


        /// <summary>
        /// 序列化对象 并返回xml字符串
        /// </summary>
        /// <param name="pipeRequestContent"></param>
        /// <returns></returns>
        public static string SerializerToString<T>(T serializerObject)
        {
            var resultxml = string.Empty;
            try
            {
                var xs = new XmlSerializer(typeof (T));
                using (var ms = new MemoryStream())
                {
                    var xtw = new XmlTextWriter(ms, Encoding.UTF8) {Formatting = Formatting.Indented};
                    xs.Serialize(xtw, serializerObject);
                    ms.Seek(0, SeekOrigin.Begin);
                    var sr = new StreamReader(ms);
                    resultxml = sr.ReadToEnd();
                    xtw.Close();
                    ms.Close();
                }
            }
            catch (Exception ex)
            {
            }
            return resultxml;
        }
    }
}